package com.yaodian100.mall.channel.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.ec.adlog.entity.AdLog;
import com.yaodian100.ec.adlog.service.AdLogService;
import com.yaodian100.ec.channel.entity.Channel;
import com.yaodian100.ec.channel.service.ChannelService;
import com.yaodian100.mall.member.util.UserData;

/**
 * 
 * @author apple.chang
 * 
 */
public class ChannelAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 689019598150039548L;

	private AdLogService adLogService;
	private ChannelService channelService;
	@Autowired
	private MenuService menuService;

	private String url;
	private String id;
	private String queryString;

	@SuppressWarnings("unchecked")
	public String ad() {
		if (StringUtils.isBlank(id)) {
			url = "/";
			return "overdue";
		}
		Channel channel = channelService.get(Long.parseLong(id));
		if (!(null != channel && channel.getStartDate().getTime() < System.currentTimeMillis()
				&& channel.getEndDate().getTime() > System.currentTimeMillis() && channel.getChannelStatus().equals("Y"))) {
			url = "/";
			return "overdue";
		}
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		if (StringUtils.isNotBlank(channel.getActUrl())) {
			url = channel.getActUrl();
		}
		if (StringUtils.isBlank(url) || (url.startsWith("http://") && !url.startsWith(ServerValue.getFrontHostname()))) {
			url = "/";
		}
		if (url.contains("?")) {
			url += "&site=" + channel.getChannelName();
		} else {
			url += "?site=" + channel.getChannelName();
		}
		url += "&chn=" + id;

		Enumeration enums = request.getParameterNames();
		while (enums.hasMoreElements()) {
			String pname = enums.nextElement().toString();
			if ("ad".equals(pname) || "hpp".equals(pname)) {
				url += "&" + pname + "=" + request.getParameter(pname);
			}
		}

		// check old apply source
		String oldAs = userData.getApplySource();
		if (StringUtils.isNotBlank(oldAs)) {
			Menu channelNameMenu = menuService.get("Channel.Name");
			if ("0".equals(channelNameMenu.getOptions().get(oldAs).getMemo1())
					&& (!"0".equals(channelNameMenu.getOptions().get(channel.getChannelName()).getMemo1()))) {
				return "redirect";
			}
		}

		queryString = request.getQueryString();
		userData.setTimeOut(60 * 60 * 24 * 30);
		userData.setApplySource(channel.getChannelName());
		userData.writeValue("ch_id", id);
		userData.writeValue("ch_child", getChannelChild(queryString));

		return "redirect";
	}

	public String adtrack() throws ParseException {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		AdLog adLog = new AdLog();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		adLog.setLogDate(df.parse(df.format(new Date())));
		adLog.setChannelId(Long.parseLong(id));
		String host = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(host)) {
			host = request.getRemoteAddr();
		}
		adLog.setClientIp(StringUtils.substring(host, 0, 100));
		adLog.setClickCount(1);
		adLogService.addAdLog(adLog);
		return "adtrack";
	}

	private String getChannelChild(String qString) {
		StringBuffer sb = new StringBuffer();
		String[] ccArray = StringUtils.split(qString, "&");
		for (int i = 0; i < ccArray.length; i++) {
			if (!(StringUtils.startsWith(ccArray[i], "url=") || StringUtils.startsWith(ccArray[i], "site=") || StringUtils
					.startsWith(ccArray[i], "id="))) {
				sb.append(sb.length() == 0 ? "" : "&").append(ccArray[i]);
			}
		}
		return sb.toString();
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getQueryString() {
		return queryString;
	}

	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}

	public AdLogService getAdLogService() {
		return adLogService;
	}

	public void setAdLogService(AdLogService adLogService) {
		this.adLogService = adLogService;
	}

	public ChannelService getChannelService() {
		return channelService;
	}

	public void setChannelService(ChannelService channelService) {
		this.channelService = channelService;
	}

}